package com.fyy.netty.chapter01.c1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author fyy
 * @Description FileChannel读取文件测试
 * @Date 2021/4/20 11:12
 */
public class FileChannelTest {

    private static Logger logger = LoggerFactory.getLogger(FileChannelTest.class);

    public static void getFileChannel(String filePath) throws IOException {
        FileChannel channel1 = null;
        try {
            channel1 = new FileInputStream(filePath).getChannel();
        } finally {
            channel1.close();
        }

    }

    public static void getFileChannel2(String filePath) throws IOException {

        try (FileChannel channel = new FileInputStream(filePath).getChannel()) {
            long position = channel.position();
            long newPositios = 100L;
            channel.position(newPositios);
        }


    }

    public static void writeChannel(String filePath,ByteBuffer buffer) throws IOException {
        //通过FileOutputStream获取channel
        FileChannel channel = new FileOutputStream(filePath).getChannel();
        buffer.put("你好".getBytes()); //填入数据
        buffer.flip(); //切换到读模式
        //为了将buffer数据全部放入，使用while
        while (buffer.hasRemaining()){
            channel.write(buffer);
        }
    }
    
    public static void main(String[] args) {
        //获取FileChannel 1.输入输出流；2.RandomAccessFile JDK提供的文本编辑工具
        try (FileChannel channel = new FileInputStream("F:\\test.txt").getChannel()) {
            //建立缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int len = 0;
            while (true){
                //从 channel 读取数据，即向 buffer 写入
                len = channel.read(buffer);
                if(len == -1){
                    break;
                }
                //打印 buffer 内容
                buffer.flip(); //切换到读模式
                logger.info("获取的内容：{}",buffer);
                while (buffer.hasRemaining()){
                    byte b = buffer.get();
                    logger.info("获取的内容：{}",(char)b);
                }
                buffer.clear(); //切换到写模式
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
